package com.yonyou.cyxdms.sysAuth.service.service.impl;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.alibaba.fastjson.JSONObject;
import com.yonyou.cyx.framework.service.http.HttpRequestService;
import com.yonyou.cyx.function.bean.dto.http.RestServiceRequestDto;
import com.yonyou.cyx.function.bean.dto.http.RestServiceResponseDto;
import com.yonyou.cyxdms.sysAuth.service.constants.UserAuthConstant;
import com.yonyou.cyxdms.sysAuth.service.dto.user.*;
import com.yonyou.cyxdms.sysAuth.service.entity.*;
import com.yonyou.cyxdms.sysAuth.service.entity.UserPO;
import com.yonyou.cyxdms.sysAuth.service.entity.cms.ConsultantParamVo;
import com.yonyou.cyxdms.sysAuth.service.entity.cms.ConsultantVo;
import com.yonyou.cyxdms.sysAuth.service.entity.cms.GetUserInfoByjwtVO;
import com.yonyou.cyxdms.sysAuth.service.entity.cms.*;
import com.yonyou.cyxdms.sysAuth.service.mapper.*;
import com.yonyou.cyxdms.sysAuth.service.mapper.cms.CMSEmployeeMapper;
import com.yonyou.cyxdms.sysAuth.service.utill.singnature.SignatureGenerator;
import com.yonyou.cyxdms.sysAuth.service.vo.user.*;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections4.ListUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonyou.cyx.framework.compent.redis.RedisClient;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.exception.DALException;
import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyx.function.utils.bean.BeanMapperUtil;
import com.yonyou.cyx.function.utils.common.CommonUtils;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyx.function.utils.jsonserializer.JSONUtil;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysAuth.service.constants.ManageDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.constants.SysAuthCommonConstants;
import com.yonyou.cyxdms.sysAuth.service.dto.role.RolePDto;
import com.yonyou.cyxdms.sysAuth.service.dto.user.EmpDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.user.LoginDto;
import com.yonyou.cyxdms.sysAuth.service.dto.user.SyncUserDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.user.UpdatePasswordDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.user.UpdateUserInfoDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.user.UserAndRoleDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.user.UserDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.user.UserEditPassword;
import com.yonyou.cyxdms.sysAuth.service.dto.user.UserInfoDto;
import com.yonyou.cyxdms.sysAuth.service.dto.user.UserParamDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.user.UserPermissionActionListDTO;
import com.yonyou.cyxdms.sysAuth.service.feign.IAuthProviderService;
import com.yonyou.cyxdms.sysAuth.service.feign.ImService;
import com.yonyou.cyxdms.sysAuth.service.feign.dto.UserInfoDTO;
import com.yonyou.cyxdms.sysAuth.service.service.UserService;
import com.yonyou.cyxdms.sysAuth.service.service.Login.UserLoginService;
import com.yonyou.cyxdms.sysAuth.service.service.jwt.JwtService;
import com.yonyou.cyxdms.sysAuth.service.service.org.OrgService;
import com.yonyou.cyxdms.sysAuth.service.service.orgposition.OrgPositionService;
import com.yonyou.cyxdms.sysAuth.service.service.role.RoleCtrlService;
import com.yonyou.cyxdms.sysAuth.service.service.role.RoleMenuActionService;
import com.yonyou.cyxdms.sysAuth.service.service.role.RoleMenuRangeService;
import com.yonyou.cyxdms.sysAuth.service.service.role.RoleService;
import com.yonyou.cyxdms.sysAuth.service.utill.MD5Util;
import com.yonyou.cyxdms.sysAuth.service.vo.employee.EmployeeAddVO;
import com.yonyou.cyxdms.sysAuth.service.vo.employee.UserEmpInfoVO;
import com.yonyou.cyxdms.sysAuth.service.vo.permission.CommonTreeStateVO;
import com.yonyou.cyxdms.sysAuth.service.vo.permission.CommonTreeVO;
import com.yonyou.cyxdms.sysAuth.service.vo.user.CompanyUserVO;
import com.yonyou.cyxdms.sysAuth.service.vo.user.DealerUserVO;
import com.yonyou.cyxdms.sysAuth.service.vo.user.QueryMCVO;
import com.yonyou.cyxdms.sysAuth.service.vo.user.UserInfosVO;
import com.yonyou.cyxdms.sysAuth.service.vo.user.UserPermissionCtrlVO;
import com.yonyou.cyxdms.sysAuth.service.vo.user.UserRoleVO;
import com.yonyou.cyxdms.sysAuth.service.vo.user.UserVO;
import com.yonyou.cyxdms.sysmanage.client.constants.BaseDataCommonConstants;
import com.yonyou.cyxdms.sysmanage.client.domains.dto.UserDictDto;
import com.yonyou.cyxdms.sysmanage.client.service.login.PushServices;
import com.yonyou.cyxdms.sysmanage.client.vo.employee.UserInfoVO;

/**
 * <p>
 * 账号信息 服务实现类
 * </p>
 *
 * @author zhangxianchao
 * @since 2018-09-13
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, UserPO> implements UserService {

    //日志对象
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    UserMapper userMapper;
    @Autowired
    EmpMapper empMapper;
    @Autowired
    TcUserMapper tcUserMapper;
    @Autowired
    PushServices pushService;
    @Autowired
    EmployeeRoleMapper employeeRoleMapper;
    @Autowired
    private OrgMapper orgMapper;
    @Autowired
    OrgPositionService orgPositionService;
    @Autowired
    RoleMenuRangeService roleMenuRangeService;
    @Autowired
    private AscInfoMapper ascInfoMapper;
    @Autowired
    RoleMenuActionService roleMenuActionService;
    @Autowired
    UserLoginService userLoginService;

    @Autowired
    private CMSEmployeeMapper cmsEmployeeMapper;

    @Autowired
    HttpRequestService httpService;

    @Autowired
    RoleCtrlService roleCtrlService;
    @Value("${sms.templateId-2}")
    private String smsTemplateId2;

    @Value("${sendConsultantToAFAPPUrl}")
    private String sendConsultantToAFAPPUrl;

    @Value("${appkey}")
    private String appkey;

    @Value("${secretkey}")
    private String secretkey;

    @Autowired
    RoleService roleService;

    @Autowired
    RoleMapper roleMapper;
    @Autowired
    EmployeeMapper employeeMapper;
    @Autowired
    OrgPositionMapper orgPositionMapper;
    @Autowired
    PermissionMenuMapper permissionMenuMapper;
    @Autowired
    PermissionMenuActionMapper permissionMenuActionMapper;
    @Autowired
    PermissionMenuRangeMapper permissionMenuRangeMapper;
    @Autowired
    MenuMapper menuMapper;
    @Autowired
    private IAuthProviderService authProviderService;
    @Autowired
    ImService imService;

    @Autowired
    UserOrgPositionMapper userOrgPositionMapper;

    @Autowired
    PermissionCtrlMapper permissionCtrlMapper;

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DealerInfoMapper dealerInfoMapper;

    @Autowired
    private OrgService orgService;

    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private UserOrgMapper userOrgMapper;

    @Autowired
    private JwtService jwtService;

    @Autowired
    private MenuRangeMapper menuRangeMapper;

    /**
     * 分页查询对应数据
     *
     * @param page           分页对象
     * @param queryCondition 查询条件
     * @author zhangxianchao
     * @since 2018/7/22 0022
     */
    @Override
    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    public IPage<Map<String, Object>> selectPageBysql(Page page, Map<String, Object> queryCondition) {
        // 获取总条数
        page.setRecords(userMapper.selectPageBySql(page, queryCondition));
        return page;
    }

    /**
     * 根据查询条件返回结果集
     *
     * @param queryCondition 查询条件
     * @author zhangxianchao
     * @since 2018/7/22 0022
     */
    @Override
    @Transactional(readOnly = true)
    public List<Map<String, Object>> selectListBySql(Map<String, Object> queryCondition) {
        return userMapper.selectListBySql(queryCondition);
    }

    /**
     * 根据查询条件返回结果集
     *
     * @param id 主键ID
     * @author zhangxianchao
     * @since 2018/7/22 0022
     */
    @Override
    @Transactional(readOnly = true)
    public Map<String, Object> getById(Long id) {
        UserPO userpo = super.getById(id);
        if (userpo != null) {
            return userpo.toMaps();
        } else {
            throw new DALException("查询失败,没有符合条件的数据");
        }
    }

    /**
     * 根据DTO 进行数据新增
     *
     * @param userDTO 页面DTO
     * @return void
     * @author zhangxianchao
     * @since 2018/7/21 0021
     */
    @Override
    public Map<String, Object> insert(UserDTO userDTO) {
        //对对象进行赋值操作
        UserPO userpo = userDTO.transDtoToPo(UserPO.class);
        //执行插入
        save(userpo);
        //返回插入的值
        return super.getById(userpo.getUserId()).toMaps();
    }

    /**
     * 根据DTO 及ID 进行数据更新
     *
     * @param id      主键ID
     * @param userDTO 页面DTO
     * @return void
     * @author zhangxianchao
     * @since 2018/7/21 0021
     */
    @Override
    public Map<String, Object> update(Long id, UserDTO userDTO) {
        UserPO userpo = super.getById(id);
        //对对象进行赋值操作
        userDTO.transDtoToPo(userpo);
        //执行更新
        this.updateById(userpo);
        return userpo.toMaps();
    }

    /**
     * 根据租户及账号信息获取用户信息
     *
     * @param appId
     * @param userCode
     * @return com.yonyou.cyx.framework.bean.dto.user_info.LoginInfoDto
     * @author zhangxianchao
     * @since 2018/9/14 0014
     */
    @Override
    @Transactional(readOnly = true)
    public LoginInfoDto getUserInfoByUserCode(String appId, String userCode) {
        LoginInfoDto loginInfoDto = userMapper.getUserInfoByCode(userCode, appId);
        if (loginInfoDto != null) {
//            String dealerCode = getDealerCodeByDealerId(Integer.parseInt(String.valueOf(loginInfoDto.getDealerId())));
//            loginInfoDto.setOwnerCode(dealerCode);
        }
        logger.debug("获取经销商信息结果：{}", loginInfoDto);
        return loginInfoDto;
    }

    /**
     * 根据EmpID 来删除用户
     *
     * @param empId @return void
     * @author zhangxianchao
     * @since 2018/9/23 0023
     */
    @Override
    public int deleteUserByEmpId(Long empId) {
        EmployeePO employeepo = employeeMapper.getByEmpId(Integer.parseInt(String.valueOf(empId)));
        return userMapper.deleteByEmployeeId(Integer.parseInt(String.valueOf(employeepo.getEmpId())));
    }

    /**
     * 根据EmpIDs 来删除用户
     *
     * @param empIds
     * @return void
     * @author zhangxianchao
     * @since 2018/9/23 0023
     */
    @Override
    public int deleteUserByBatchEmpIds(List<Long> empIds) {
        int deleteCount = 0;
        logger.debug("empIds:{}", empIds);
        for (int i = 0; i < empIds.size(); i++) {
            int deleteFlag = deleteUserByEmpId(empIds.get(i));
            deleteCount += deleteFlag;
        }
        return deleteCount;
    }

    @Override
    public UserInfoDto viliateUserPass(LoginDto loginDto) {
        Map<String, Object> info = userMapper.getUserInfoByPass(loginDto.getUserName(), loginDto.getPassWord(), loginDto.getAppId());
        if (MapUtils.isEmpty(info)) {
            throw new ServiceBizException("登录信息错误");
        }
        UserInfoDto res = new UserInfoDto();
        res.setKickOut(true);
        res.setName(loginDto.getUserName());
        res.setUserId(Integer.valueOf(info.get("userId").toString()));
        res.setUserName(info.get("name") == null ? "" : info.get("name").toString());
        res.setTelPhone(info.get("phone") == null ? "" : info.get("phone").toString());
        res.setDealerName(info.get("dealerName") == null ? "" : info.get("dealerName").toString());
        res.setDealerCode(info.get("dealerCode") == null ? "" : info.get("dealerCode").toString());
        res.setAppId(info.get("appId") == null ? "" : info.get("appId").toString());
        return res;
    }

    /**
     * 通过userCode获取userID
     *
     * @param userCode
     * @return java.lang.Long
     * @author zhangsx
     * @since 2018/11/8
     */
    @Override
    public Long getUserInfoByParams(String userCode, String appId) {

        LambdaQueryWrapper<UserPO> queryWrapper = new QueryWrapper().lambda();
        queryWrapper.eq(UserPO::getUserCode, userCode);
        queryWrapper.eq(UserPO::getAppId, appId);

        UserPO userInfo = getOne(queryWrapper);
        Long userId = userInfo == null ? 0 : Long.parseLong(String.valueOf(userInfo.getUserId()));
        logger.info("查询的对应userId===:{}", userId);
        return userId;
    }

    @Override
    @Transactional
    public Long syncUser(SyncUserDTO syncUserDTO) {
        Long id = 0L;

        EmpDTO empDTO = syncUserDTO.getEmpDTO();
        UserDTO userDTO = syncUserDTO.getUserDTO();
        if (syncUserDTO.getIntsOrUp()) {
            EmpPo empPo = new EmpPo(empDTO);
            empPo.setUserCode(userDTO.getUserCode());
            // empPo.setPassword(userDTO.getPassword());
            empMapper.insert(empPo);

            EmployeePO employeepo = new EmployeePO();
            employeeMapper.insert(employeepo);

            UserPO userpo = new UserPO(userDTO);
            userpo.setEmpId(employeepo.getEmpId().intValue());
            userMapper.insert(userpo);
            id = Long.parseLong(String.valueOf(userpo.getUserId()));
        } else {
            UserPO userpo1 = userMapper.selectById(userDTO.getUserId());
            EmployeePO employeepo1 = employeeMapper.selectById(userpo1.getEmpId());
            EmpPo empPo1 = empMapper.selectById(employeepo1.getEmpId());

            EmpPo empPo = new EmpPo(empDTO);
            BeanUtils.copyProperties(empPo, empPo1);
            empPo1.setUserCode(userDTO.getUserCode());
            //  empPo1.setPassword(userDTO.getPassword());
            empMapper.updateById(empPo1);

            EmployeePO employeepo = new EmployeePO();
            BeanUtils.copyProperties(employeepo, employeepo1);
            employeeMapper.updateById(employeepo1);

            UserPO userpo = new UserPO(userDTO);
            userpo.setEmpId(employeepo.getEmpId().intValue());
            userMapper.updateById(userpo);
        }
        logger.info("新增用户的id:{}", id);
        return id;
    }

    @Transactional
    @Override
    public Boolean updateUserInfo(UpdateUserInfoDTO updateUserInfoDTO) {
        //获取登陆信息
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);

        UserPO userpo = userMapper.selectByAppUserId(loginInfoDto.getAppId(), loginInfoDto.getUserId());
        if (userpo == null) {
            return false;
        }

        EmployeePO employeepo = employeeMapper.selectById(userpo.getEmpId());
//        employeePO.setCertificateId(updateUserInfoDTO.getCertificateId());
//        employeePO.setPhone(updateUserInfoDTO.getPhone());
//        employeePO.setGender(updateUserInfoDTO.getGender());
//        employeePO.setEmployeeName(updateUserInfoDTO.getName());
        employeeMapper.updateById(employeepo);

        EmpPo empPo = empMapper.selectById(employeepo.getEmpId());
//        empPo.setCertificateId(updateUserInfoDTO.getCertificateId());
//        empPo.setPhone(updateUserInfoDTO.getPhone());
        empPo.setGender(updateUserInfoDTO.getGender());
        empPo.setEmployeeName(updateUserInfoDTO.getName());
        empMapper.updateById(empPo);

        // fixme 把用户信息同步到im
        imService.saveOrUpdate(setSyncImUserDTO(empPo, userpo, loginInfoDto, updateUserInfoDTO));
        logger.debug("人员信息同步到IM完成");
        logger.debug("人员信息同步到broker完成");

        return true;
    }

    private UserInfoDTO setSyncImUserDTO(EmpPo emppo, UserPO user, LoginInfoDto loginInfoDto,
                                         UpdateUserInfoDTO updateUserInfoDTO) {
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        userInfoDTO.setUserId(Long.parseLong(String.valueOf(user.getUserId())));
        userInfoDTO.setAppId(user.getAppId());
        userInfoDTO.setUserToken(user.getUserId().toString());
        userInfoDTO.setUserName(emppo.getEmployeeName());
        userInfoDTO.setIsStop(0);
        userInfoDTO.setDealerCode(loginInfoDto.getOwnerCode());
        userInfoDTO.setPhone(emppo.getMobilePhone());
        userInfoDTO.setUserCode(updateUserInfoDTO.getEmployeeNo());
        userInfoDTO.setEmployeeNo(updateUserInfoDTO.getEmployeeNo());
        logger.info("组装IM人员信息完成，准备同步：{}", JSON.toJSON(userInfoDTO));

        return userInfoDTO;
    }

    @Override
    public Boolean updatePassword(UpdatePasswordDTO updatePasswordDTO) {
        //获取登陆信息
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);

        UserPO userpo = userMapper.selectByAppUserId(loginInfoDto.getAppId(), loginInfoDto.getUserId());
        if (userpo == null || !userpo.getPassword().equals(updatePasswordDTO.getPassword())) {
            return false;
        }

        userpo.setPassword(updatePasswordDTO.getNewPassword());
        userMapper.updateById(userpo);

        return true;
    }

    @Override
    public Long getDealerId(Long userId) {
        Integer dealerId = userMapper.getDealerIdByUserId(Integer.parseInt(String.valueOf(userId)));
        return Long.parseLong(String.valueOf(dealerId));
    }

    @Override
    public Map<String, Object> userDataVue(String employeeId, String dataSource1) {
        String dataSource = ApplicationContextHelper.getBeanByType(LoginInfoDto.class).getDataType().toString();
        //EmployeePO employeePO = employeeMapper.selectById(employeeId);
        Map<String, Object> userData = new HashMap<>();
        LambdaQueryWrapper<UserPO> queryWrapper = new QueryWrapper<UserPO>().lambda();
        queryWrapper.eq(UserPO::getEmpId, employeeId);
        Integer userId = userMapper.selectList(queryWrapper).get(0).getUserId();
        Integer isFixed = userMapper.getDealerIsFixed(userMapper.selectList(queryWrapper).get(0).getCompanyId());
        String appId = userMapper.selectList(queryWrapper).get(0).getAppId();
        if (userId == null) {
            if (!StringUtils.isEquals(ManageDictCodeConstants.STATUS_IS_YES, isFixed.toString())) {// 非固化的
                List<Map> list = menuMapper.queryMenuByType(appId);
                List<CommonTreeVO> orgList = new ArrayList<>();
                for (int i = 0; i < list.size(); i++) {
                    CommonTreeVO orgTreeOrg = new CommonTreeVO();
                    orgTreeOrg.setId((String) list.get(i).get("menuId").toString());
                    String parent = (String) list.get(i).get("parentId").toString();
                    if ("0".equals(parent)) {
                        parent = "#";
                    }
                    orgTreeOrg.setParent(parent);
                    orgTreeOrg.setText((String) list.get(i).get("menuName").toString());
                    orgList.add(orgTreeOrg);
                }
                Map<String, String> checkbox = new HashMap<String, String>();
                String[] treeMenuActionString = new String[0];
                String[] treeMenuRangeString = new String[0];
                userData.put("treejson", orgList);
                userData.put("checkbox", checkbox);
                userData.put("treeMenuAction", treeMenuActionString);
                userData.put("treeMenuRange", treeMenuRangeString);
            } else {// 固化的

                String[] treeMenuActionString = new String[0];
                String[] treeMenuRangeString = new String[0];
                userData.put("treeMenuAction", treeMenuActionString);
                userData.put("treeMenuRange", treeMenuRangeString);
            }

        } else {
            // 如果是集团下发的用户，那么根据用户id去找到所对应的角色
            if (StringUtils.isEquals(dataSource, "10451003")) {
                //通过userid获取用户权限
                String ids = userOrgPositionMapper.queryRoleIds(userId).get("roleIds").toString();
                String[] idsArray = null;
                if (!StringUtils.isNullOrEmpty(ids)) {
                    idsArray = ids.split(",");
                }
                Map<String, Object> params = new HashMap<>();
                params.put("idsArray", idsArray);
                Map<String, String> checkbox = queryMenuCtrl(ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE, params);
                List<CommonTreeVO> orgList = queryPermissionMenu(ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE, params, isFixed);
                userData.put("treejson", orgList);
                userData.put("checkbox", checkbox);
                userData.put("treeMenuAction", findMenuAction(ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE, params));
                userData.put("treeMenuRange", findMenuRange(ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE, params));
            } else {
                String[] idsArray = {Long.toString(userId)};
                Map<String, Object> params = new HashMap<>();
                params.put("idsArray", idsArray);
                Map<String, String> checkbox = queryMenuCtrl(ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, params);// you
                List<CommonTreeVO> orgList = queryPermissionMenu(ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, params, isFixed);
                userData.put("treejson", orgList);
                userData.put("checkbox", checkbox);
                userData.put("treeMenuAction", findMenuAction(ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, params));
                userData.put("treeMenuRange", findMenuRange(ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, params));
            }
        }
        return userData;
    }

    Map<String, String> queryMenuCtrl(Integer permissionType, Map<String, Object> params) {
        String maintain = null;//维修
        String accessories = null;//配件
        String vehicleWarehouse = null;//整车仓库
        String accessoriesWarehouse = null;//配件仓库
        String suppliesWarehouse = null;//用品仓库
        String favorableModels = null;//优惠模式
        String checkedListSettlement = null;// 结算1314
        String checkedListMaintenanceType = null;// 维修类型

        String claimWarehouse = null;// 索赔回运仓库

        List<QueryMCVO> list = permissionCtrlMapper.queryMCtrl(permissionType, params);
        System.out.println("list = " + list);
        Map<String, String> basicresult = new HashMap<>();
        for (QueryMCVO querymcvo : list) {

            String ctrlCode = querymcvo.getCtrlCode();
            Integer type = querymcvo.getType();
            if (type.equals(ManageDictCodeConstants.MAINTAIN)) {
                if (maintain == null) {
                    maintain = ctrlCode;
                } else {
                    maintain += ",";
                    maintain += ctrlCode;
                }
            }
            if (type.equals(ManageDictCodeConstants.ACCESSORIES)) {

                if (accessories == null) {
                    accessories = ctrlCode;
                } else {
                    accessories += ",";
                    accessories += ctrlCode;
                }
            }
            if (type.equals(ManageDictCodeConstants.VEHICLE_WAREHOUSE)) {
                if (vehicleWarehouse == null) {
                    vehicleWarehouse = ctrlCode;
                } else {
                    vehicleWarehouse += ",";
                    vehicleWarehouse += ctrlCode;
                }
            }
            if (type.equals(ManageDictCodeConstants.ACCESSORIES_WAREHOUSE)) {
                if (accessoriesWarehouse == null) {
                    accessoriesWarehouse = ctrlCode;
                } else {
                    accessoriesWarehouse += ",";
                    accessoriesWarehouse += ctrlCode;
                }
            }
            if (type.equals(ManageDictCodeConstants.CLAIM_WAREHOUSE)) {
                if (claimWarehouse == null) {
                    claimWarehouse = ctrlCode;
                } else {
                    claimWarehouse += ",";
                    claimWarehouse += ctrlCode;
                }
            }
            if (type.equals(ManageDictCodeConstants.SUPPLIES_WAREHOUSE)) {
                if (suppliesWarehouse == null) {
                    suppliesWarehouse = ctrlCode;
                } else {
                    suppliesWarehouse += ",";
                    suppliesWarehouse += ctrlCode;
                }
            }
            if (type.equals(ManageDictCodeConstants.FAVORABLE_MODELS)) {
                if (favorableModels == null) {
                    favorableModels = ctrlCode;
                } else {
                    favorableModels += ",";
                    favorableModels += ctrlCode;
                }
            }

            if (type.equals(ManageDictCodeConstants.SETTLEMENT)) {
                if (checkedListSettlement == null) {
                    checkedListSettlement = ctrlCode;
                } else {
                    checkedListSettlement += ",";
                    checkedListSettlement += ctrlCode;
                }
            }

            if (type.equals(ManageDictCodeConstants.CHECKED_LIST_MAINTENANCE_TYPE)) {
                if (checkedListMaintenanceType == null) {
                    checkedListMaintenanceType = ctrlCode;
                } else {
                    checkedListMaintenanceType += ",";
                    checkedListMaintenanceType += ctrlCode;
                }
            }

        }
        basicresult.put("maintain", maintain);
        basicresult.put("accessories", accessories);
        basicresult.put("vehicleWarehouse", vehicleWarehouse);
        basicresult.put("accessoriesWarehouse", accessoriesWarehouse);
        basicresult.put("claimWarehouse", claimWarehouse);
        basicresult.put("suppliesWarehouse", suppliesWarehouse);
        basicresult.put("favorableModels", favorableModels);
        basicresult.put("checkedListSettlement", checkedListSettlement);
        basicresult.put("checkedListMaintenanceType", checkedListMaintenanceType);
        return basicresult;
    }

    List<CommonTreeVO> queryPermissionMenu(Integer permissionType, Map<String, Object> params, Integer isFixed) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Integer orgType = loginInfoDto.getDataType().intValue();
        String[] s = (String[]) params.get("idsArray");

        List<Map> listmap;

        String userOrgId = s[0];

        listmap = permissionMenuMapper.queryPermissionMenu4(orgType, permissionType, userOrgId, loginInfoDto.getAppId());
        //}
        Iterator<Map> it = listmap.iterator();
        List<CommonTreeVO> orgList = new ArrayList<CommonTreeVO>();
        while (it.hasNext()) {
            CommonTreeVO orgTreeOrg = new CommonTreeVO();
            CommonTreeStateVO commonTreeStateVO = new CommonTreeStateVO();
            Map menuMap = it.next();
            orgTreeOrg.setId(menuMap.get("menuId").toString());
            String parent = menuMap.get("parendId").toString();
            if ("0".equals(parent)) {
                parent = "#";
            }
            if (!StringUtils.isNullOrEmpty(menuMap.get("isEmpowered"))
                    && StringUtils.isEquals(ManageDictCodeConstants.STATUS_IS_YES, menuMap.get("isEmpowered").toString())) {
                Long menuId = (Long) menuMap.get("menuId");
                if (menuId > 99999) {
                    commonTreeStateVO.setChecked(true);
                } else {
                    commonTreeStateVO.setChecked(false);
                }
            } else {
                commonTreeStateVO.setChecked(false);
            }
            if (!StringUtils.isNullOrEmpty(menuMap.get("isFlexible")) && !StringUtils.isEquals(ManageDictCodeConstants.STATUS_IS_YES, menuMap.get("isFlexible").toString())) {
                commonTreeStateVO.setCheckboxDisabled(true);
            }
            if (!StringUtils.isNullOrEmpty(menuMap.get("isFlexible")) && StringUtils.isEquals(ManageDictCodeConstants.STATUS_IS_YES, menuMap.get("isFlexible").toString())) {
                menuMap.put("menuName", menuMap.get("menuName").toString());
            }
            //2019-8-9修改增加 柔性权限修改，通过经销商的参数配置，来设置柔性权限的修改
            if (!StringUtils.isNullOrEmpty(menuMap.get("isFlexible")) && StringUtils.isEquals(ManageDictCodeConstants.STATUS_IS_YES, menuMap.get("isFlexible").toString()) && StringUtils.isEquals(ManageDictCodeConstants.STATUS_IS_YES, isFixed.toString())) {
                commonTreeStateVO.setDisabled(true);
            }
            orgTreeOrg.setParent(parent);
            orgTreeOrg.setText(menuMap.get("menuName").toString());
            orgTreeOrg.setState(commonTreeStateVO);
            orgList.add(orgTreeOrg);
        }
        return orgList;
    }

    /**
     * 查询操作按钮
     *
     * @param permissionType
     * @param params
     * @author maxingjian
     * @since 2019/07/11
     */
    String[] findMenuAction(Integer permissionType, Map<String, Object> params) {
        List<Map> listmap = permissionMenuActionMapper.findMenuAction(permissionType, params);
        String[] treeMenuAction = new String[listmap.size()];
        for (int i = 0; i < listmap.size(); i++) {
            String oneAction = null;
            Map map = listmap.get(i);
            String actionCode = (String) map.get("actionCode");//去重
            String aaArray[] = actionCode.split(",");
            HashSet<String> hs = new HashSet<>();
            for (String s : aaArray) {
                hs.add(s);
            }
            Iterator<String> it = hs.iterator();
            if (it.hasNext()) {
                actionCode = hs.toString().replace("[", "").replace("]", "");//去除相同项的字符串
            }
            oneAction = map.get("menuId") + "-" + actionCode;
            treeMenuAction[i] = oneAction;
        }
        return treeMenuAction;
    }

    String[] findMenuRange(Integer permissionType, Map<String, Object> params) {
        List<Map> listmap = permissionMenuRangeMapper.findMenuRange(permissionType, params);
        String[] treeMenuRange = new String[listmap.size()];
        for (int i = 0; i < listmap.size(); i++) {
            String oneRange = null;
            Map map = listmap.get(i);

            String rangeCode = map.get("rangeCode").toString();//去重
            String aaArray[] = rangeCode.split(",");
            HashSet<String> hs = new HashSet<>();
            for (String s : aaArray) {
                hs.add(s);
            }
            Iterator<String> it = hs.iterator();
            if (it.hasNext()) {
                rangeCode = hs.toString().replace("[", "").replace("]", "");//去除相同项的字符串
            }

            oneRange = map.get("menuId") + "-" + rangeCode;
            treeMenuRange[i] = oneRange;

        }
        return treeMenuRange;
    }

    @Override
    public Integer getDealerIdByDealerCode(String dealerCode) {
        return userMapper.getDealerIdByDealerCode(dealerCode);
    }

    @Override
    public String getDealerCodeByDealerId(Integer dealerId) {
        return userMapper.getDealerCodeByDealerId(dealerId);
    }

    /**
     * 查询登录用户信息
     *
     * @return
     * @author 李贺
     * @date 2019年9月18日
     */
    @Override
    public EmployeeAddVO findByEmployeeId() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return employeeMapper.findEmployeeByNo(loginInfoDto.getEmployeeNo(), loginInfoDto.getAppId(), loginInfoDto.getCompanyId());
    }

    /**
     * @author ：quankk
     * @date ：2019/7/12 15:40
     * @description：
     */
    @Override
    public Long editpassword(UserVO userDto) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        String userCode = loginInfoDto.getUserCode();
        String password = userDto.getPassword();
        String newPassword = userDto.getNewPassword();
        LambdaQueryWrapper<UserPO> lambdaQueryWrapper = new QueryWrapper<UserPO>().lambda();
        lambdaQueryWrapper.eq(UserPO::getUserCode, userCode).eq(UserPO::getAppId, loginInfoDto.getAppId());
        UserPO empPo = userMapper.selectOne(lambdaQueryWrapper);
        String encryptedPwd = MD5Util.getEncryptedPwd(password);
        System.out.println("encryptedPwd = " + encryptedPwd);
        String passwordmd5 = empPo.getPassword();
        boolean validation = MD5Util.validPassword(password, passwordmd5);
        if (validation) {
            String newpasswordmd5 = MD5Util.getEncryptedPwd(newPassword);
            Long id = empMapper.getEmployeeIdByUserCode(userCode, loginInfoDto.getAppId());
            userDto.setPassword(newpasswordmd5);
            userDto.setEmployeeId(id);
            // 启用状态
            userDto.setUserStatus(ManageDictCodeConstants.STATUS_QY);
            // 锁定状态
            userDto.setLockFlag(ManageDictCodeConstants.STATUS_IS_NOT);
            empPo.setLoginLastTime(LocalDateTime.now());
            if (!StringUtils.isNullOrEmpty(userDto.getPassword())) {
                empPo.setPassword(userDto.getPassword());
            }
            empPo.setUserStatus(userDto.getUserStatus());
            empPo.setUpdatePasswordDate(LocalDateTime.now());
            userMapper.updateById(empPo);

            return id;
        } else {
            throw new ServiceBizException("原密码不正确");
        }
    }

    @Override
    public RolePDto modifyOrg(RolePDto rolePDto) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
//        Long employeeId = rolePDto.getEmployeeId();
//        logger.debug("用户权限开始1===>获取employeeId" + employeeId);
//        List<Map> list = userMapper.findUserIdByEmployeeId(employeeId);
//        if (list.size() > 0) {
//            Long userId = Long.parseLong(list.get(0).get("userId").toString());
//            if (StringUtils.isNullOrEmpty(userId)) {
//                List<Map> user = userMapper.getUserTypeByUserCode(rolePDto.getUserCode(),loginInfoDto.getAppId());
//                if (!CommonUtils.isNullOrEmpty(user)) {
//                    throw new ServiceBizException("账号已存在!");
//                }
//            }
//        }
        logger.debug("用户权限2===>更新权限操作开始");
        // 更新权限操作替换到下面方法中
        modifyPermission(rolePDto);
        return rolePDto;
    }

    public void modifyPermission(RolePDto rolepdto) {

        String roleId = rolepdto.getNowRole();
        Long employeeId = rolepdto.getEmployeeId();//员工id，用来查下面是否有账户
        String employeeRoleIds = rolepdto.getEmployeeRoleIds();//用户对应的角色ID
        List<String> employeeRoles = rolepdto.getEmployeeRoles();//员工职位信息
        Long userId = getuseridbyemployeeid(employeeId).longValue();//userid
        String userCode = rolepdto.getUserCode();//账号
        String employeeName = rolepdto.getEmployeeName();//姓名
        String password = rolepdto.getPassword();//密码
        String userStatus = rolepdto.getUserStatus();//有效无效
        String nowTree = rolepdto.getNowTree();
        String treeMenuAction = rolepdto.getTreeMenuAction();
        String treeMenuRange = rolepdto.getTreeMenuRange();/////
        List<String> maintain = rolepdto.getMaintain();
        List<String> accessories = rolepdto.getAccessories();
        List<String> vehicleWarehouse = rolepdto.getVehicleWarehouse();//整车仓库
        List<String> accessoriesWarehouse = rolepdto.getAccessoriesWarehouse();//配件仓库
        List<String> suppliesWarehouse = rolepdto.getSuppliesWarehouse();//用品仓库
        List<String> favorableModels = rolepdto.getFavorableModels();

        if (StringUtils.isNullOrEmpty(nowTree)) {//菜单权限不能为空
            throw new ServiceBizException("菜单权限不能为空");
        }
        //如果员工下面没有账户，新建一个账户
        if (userId == 0) {
            //插入tc_user数据
            insertTcUser(userCode);
            //修改员工
            updateEmpAndEmployee(employeeId, userCode);
            //修改用户--begin--
            UserPO userpo = new UserPO();
            userpo.setEmpId(employeeId.intValue());
            userpo.setUserCode(userCode);
            if (StringUtils.isNullOrEmpty(userStatus)) {
                userpo.setUserStatus(ManageDictCodeConstants.STATUS_QY);
            } else {
                userpo.setUserStatus(Integer.parseInt(userStatus));
            }
            userMapper.insert(userpo);
            //--end--
            userId = userpo.getUserId().longValue();
            //再查一次新建账户id
            Long userIdtwice = Long.parseLong(userMapper.findUserIdByEmployeeId(employeeId).get(0).get("userId").toString());
            String useridtwice = Long.toString(userIdtwice);//类型转换
            //账号密码转移到了emp中
            orgPositionService.adduserpositionsperdms(userId, employeeRoleIds, ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, maintain, accessories);

            userPer(nowTree, userIdtwice, maintain, accessories, vehicleWarehouse, accessoriesWarehouse, favorableModels, suppliesWarehouse, treeMenuAction, useridtwice, treeMenuRange);
        } else {//如果账户已有
            updateEmpById(employeeId, employeeRoles);
            //获取当前锁定状态
            LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
            LambdaQueryWrapper<UserPO> lambdaQueryWrapper = new QueryWrapper().lambda();
            lambdaQueryWrapper.eq(UserPO::getEmpId, employeeId).eq(UserPO::getAppId, loginInfoDto.getAppId());
            UserPO userpo = userMapper.selectOne(lambdaQueryWrapper);
            userpo.setEmpId(employeeId.intValue());
            userpo.setUserCode(userCode);
            if (StringUtils.isNullOrEmpty(userStatus)) {
                userStatus = ManageDictCodeConstants.STATUS_QY + "";
            }
            userpo.setUserStatus(Integer.parseInt(userStatus));
            userMapper.updateById(userpo);
            String userid = Long.toString(userId);//类型转换
            //如果改变checkbox才做操作
            orgPositionService.adduserpositionsperdms(userId, employeeRoleIds, ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, maintain, accessories);

            userPer(nowTree, userId, maintain, accessories, vehicleWarehouse, accessoriesWarehouse, favorableModels, suppliesWarehouse, treeMenuAction, userid, treeMenuRange);

        }

    }

    //保存tc_USER
    @Override
    public void insertTcUser(String userCode) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        TcUserPO tcuserpo = new TcUserPO();
        tcuserpo.setOwnerCode(loginInfoDto.getOwnerCode());
        //tcUserPO.setGroupCode(loginInfoDto.getGroupCode());
        tcuserpo.setUserCode(userCode);
        tcuserpo.setUserType(1);
        tcuserpo.setAppId(loginInfoDto.getAppId());
        tcUserMapper.insert(tcuserpo);
    }

    //更新emp表和employee表、
    @Override
    public void updateEmpAndEmployee(Long employeeId, String userCode) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        if (userMapper.getEmpByUserCode(userCode, loginInfoDto.getAppId()).size() != 0) {
            throw new ServiceBizException("该账号已存在");
        }
        EmployeePO employeepo = employeeMapper.selectById(employeeId);
        employeepo.setDataType(ManageDictCodeConstants.DATA_TYPE_BY_OWNER);
        employeeMapper.updateById(employeepo);
        EmpPo emppo = empMapper.selectById(employeepo.getEmpId());
        emppo.setUserCode(userCode);
        //   emppo.setLockFlag(ManageDictCodeConstants.STATUS_IS_NOT);
        //   emppo.setFailureNum(0);
        //MD5加密
        String passwordmd5 = MD5Util.getEncryptedPwd(ManageDictCodeConstants.LOGIN_PW);
        //   emppo.setPassword(PasswordMD5);
        empMapper.updateById(emppo);
    }

    @Override
    public Integer getuseridbyemployeeid(Long employeeId) {
        LambdaQueryWrapper<UserPO> queryWrapper = new QueryWrapper<UserPO>().lambda();
        queryWrapper.eq(UserPO::getEmpId, employeeId);
        List<UserPO> list = userMapper.selectList(queryWrapper);
        Integer userId = 0;
        if (list.size() > 0) {
            userId = list.get(0).getUserId();
        }
        return userId;
    }

    /**
     * @author ：quankk
     * @date ：2019/7/18 15:22
     * @description：用户密码查询用户信息
     */
    @Override
    public IPage<UserInfosVO> searchUserInfos(Page<UserInfosVO> page, Map<String, String> param) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        param.put("appId", loginInfoDto.getAppId());
        List<UserInfosVO> list = userMapper.searchUserInfos(page, param);
        page.setRecords(list);
        return page;
    }

    /**
     * @author ：quankk
     * @date ：2019/7/18 16:01
     * @description：修改密码
     */
    @Override
    public void editPassword(UserEditPassword userEditPassword) {
        String newpasswordmd5 = MD5Util.getEncryptedPwd(userEditPassword.getNewPassword());
        String[] empIds = userEditPassword.getEmpIds().split(",");
        for (String empId : empIds) {
            EmpPo empPo = empMapper.selectById(empId);
            //   empPo.setPassword(newPasswordMD5);
            empMapper.updateById(empPo);
        }
    }

    /**
     * @author ：quankk
     * @date ：2019/7/18 16:21
     * @description：重置密码
     */
    @Override
    public void restPassword(UserEditPassword userEditPassword) {
        userEditPassword.setNewPassword(SysAuthCommonConstants.LOGIN_PW);
        editPassword(userEditPassword);
    }

    public void userPer(String nowTree, Long userId, List<String> maintain, List<String> accessories, List<String> vehicleWarehouse, List<String> accessoriesWarehouse, List<String> favorableModels, List<String> suppliesWarehouse, String treeMenuAction, String userid, String treeMenuRange) {

        //如果改变checkbox才做操作
        orgPositionService.emptyPositionById(userId, ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER);
        String[] sourceStrArray = nowTree.split(",");
        for (int i = 0; i < sourceStrArray.length; i++) {
            roleService.editPermissionMenu(ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, userid, Long.parseLong(sourceStrArray[i]));
        }

        if (!CommonUtils.isNullOrEmpty(maintain)) {
            for (int i = 0; i < maintain.size(); i++) {
                roleCtrlService.editPermissionCtrl(ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, userid, maintain.get(i), ManageDictCodeConstants.MAINTAIN);

            }
        }
        if (!CommonUtils.isNullOrEmpty(accessories)) {
            for (int i = 0; i < accessories.size(); i++) {
                roleCtrlService.editPermissionCtrl(ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, userid, accessories.get(i), ManageDictCodeConstants.ACCESSORIES);

            }
        }
        if (!CommonUtils.isNullOrEmpty(vehicleWarehouse)) {
            roleCtrlService.deleteMenuByPermissionId(ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, userid, ManageDictCodeConstants.VEHICLE_WAREHOUSE);
            for (int i = 0; i < vehicleWarehouse.size(); i++) {
                roleCtrlService.addPermissionCtrl(ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, userid, vehicleWarehouse.get(i), ManageDictCodeConstants.VEHICLE_WAREHOUSE);
            }
        }
        if (!CommonUtils.isNullOrEmpty(accessoriesWarehouse)) {
            roleCtrlService.deleteMenuByPermissionId(ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, userid, ManageDictCodeConstants.ACCESSORIES_WAREHOUSE);
            for (int i = 0; i < accessoriesWarehouse.size(); i++) {
                roleCtrlService.addPermissionCtrl(ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, userid, accessoriesWarehouse.get(i), ManageDictCodeConstants.ACCESSORIES_WAREHOUSE);
            }
        }
        if (!CommonUtils.isNullOrEmpty(favorableModels)) {
            roleCtrlService.deleteMenuByPermissionId(ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, userid, ManageDictCodeConstants.FAVORABLE_MODELS);
            for (int i = 0; i < favorableModels.size(); i++) {
                roleCtrlService.addPermissionCtrl(ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, userid, favorableModels.get(i), ManageDictCodeConstants.FAVORABLE_MODELS);

            }
        }
        //treeMenuAction
        if (treeMenuAction != null && treeMenuAction != "") {
            String[] oneAction = treeMenuAction.split(";");
            if (oneAction.length > 0) {
                for (int i = 0; i < oneAction.length; i++) {
                    if (!StringUtils.isNullOrEmpty(oneAction[i])) {
                        roleMenuActionService.editOneAction(oneAction[i], ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, userid);
                    }
                }
            }
        }
        //treeMenuRange
        if (treeMenuRange != null && treeMenuRange != "") {
            String[] oneRange = treeMenuRange.split(";");
            if (oneRange.length > 0) {
                for (int i = 0; i < oneRange.length; i++) {
                    if (!StringUtils.isNullOrEmpty(oneRange[i])) {
                        roleMenuRangeService.editOneRange(oneRange[i], ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, userid);

                    }
                }
            }
        }
    }

    @Override
    public void updateEmpById(Long id, List<String> employeeRoles) throws ServiceBizException {
        // 删除之前保存的员工全部角色信息
        List<String> roles = employeeRoles;
        employeeRoleMapper.delEmployeeRoleByEmpId(id);
        EmployeeRolePO erPo = null;
        // 保存修改之后的员工角色信息
        if (roles.size() > 0) {
            for (int i = 0; i < roles.size(); i++) {
                erPo = new EmployeeRolePO();
                erPo.setEmployeeId(id.intValue());
                erPo.setRole(Integer.parseInt(roles.get(i)));
                employeeRoleMapper.insert(erPo);
            }
        }

    }

    /**
     * @author ：quankk
     * @date ：2019/7/24 19:58
     * @description：
     */
    @Override
    public Long supereditpassword(UserVO userDto) {
        Long id = userDto.getEmployeeId();
        EmployeePO employeepo = employeeMapper.selectById(id);
        // 获取当前账号的锁定状态
        LambdaQueryWrapper<UserPO> queryWrapper = new QueryWrapper().lambda();
        queryWrapper.eq(UserPO::getEmpId, employeepo.getEmpId());
        UserPO userpo = userMapper.selectList(queryWrapper).get(0);
        userpo.setUserStatus(ManageDictCodeConstants.STATUS_QY);
        userpo.setLoginLastTime(LocalDateTime.now());
        userpo.setPassword(MD5Util.getEncryptedPwd(userDto.getNewPassword()));
        userMapper.updateById(userpo);
        //Integer empId = employeePO.getEmpId();
        //EmpPo empPo = empMapper.selectById(empId);
        //empPo.setUserStatus(ManageDictCodeConstants.STATUS_QY);
        //    empPo.setLoginLastTime(new Date());
        //     empPo.setPassword(MD5Util.getEncryptedPwd(userDto.getNewPassword()));
        //empMapper.updateById(empPo);
        return id;
    }

    /**
     * @author ：MAXIGJIAN
     * @date ：2019/8/13 19:58
     * @description：
     */
    @Override
    public UserDictDto getUserById(Long userId) {
        String messageFormat = BaseDataCommonConstants.USER_CACHE_USERID;
        Object userDictDto = redisClient.hget(messageFormat, userId.toString());
        if (userDictDto == null) {
            if (userId < 0) {
                UserDictDto userDto = new UserDictDto();
                userDto.setUserId(-1L);
                redisClient.hsetExpire(messageFormat, "-1", JSONUtil.objectToJson(userDto),
                        SysAuthCommonConstants.EXPIRE_TIME_ONE_DAY);
            } else {
                //所有数据
                userDictDto = userMapper.getUserById(userId);
                logger.info("查询用户Dto:{}", userDictDto);
                if (userDictDto == null) {
                    return null;
                }
                redisClient.hsetExpire(messageFormat, userId.toString(), JSONUtil.objectToJson(userDictDto), SysAuthCommonConstants.EXPIRE_TIME_ONE_DAY);

            }
        }
        return JSONUtil.jsonToObj(JSONUtil.objectToJson(userDictDto), UserDictDto.class);
    }

    @Override
    public UserDictDto getuserbyidcms(Long userId) {
        String messageFormat = BaseDataCommonConstants.USER_CACHE_USERID_CMS;
        Object userDictDto = redisClient.hget(messageFormat, userId.toString());
        if (userDictDto == null) {
            //所有数据
            userDictDto = userMapper.getUserByIdCMS(userId);
            logger.info("查询用户Dto:{}", userDictDto);
            if (userDictDto == null) {
                return null;
            }
            redisClient.hsetExpire(messageFormat, userId.toString(), JSONUtil.objectToJson(userDictDto), SysAuthCommonConstants.EXPIRE_TIME_ONE_DAY);
        }
        return JSONUtil.jsonToObj(JSONUtil.objectToJson(userDictDto), UserDictDto.class);
    }

    @Override
    public GetUserInfoByjwtVO getuserinfobyuid(String userId) {
        List<GetUserInfoByjwtVO> list = userMapper.getUserInfoByUId(userId);

        Map<String, String> map = new HashMap<>();
        map.put("前台接待", "10061011");
        map.put("网销顾问", "10061012");
        map.put("展厅主管", "10061013");
        map.put("销售顾问", "10061015");
        map.put("网销经理", "10061019");
        String roleCode = "";
        for (GetUserInfoByjwtVO vo : list) {
            String code = vo.getRoleCode();
            if (!StringUtils.isNullOrEmpty(code)) {
                String val = map.get(code);
                roleCode = roleCode + val + ",";
            }
        }
        if (!list.isEmpty()) {
            List<UserInfoInterZhiHuiRoleMapCp> roleList = cmsEmployeeMapper.getUserInfoRoleAll(UserAuthConstant.APP_SOURCE_BEIJING);
            for (GetUserInfoByjwtVO vo : list) {
                List<Map<String, String>> addList = new ArrayList<>();
                Map<String, String> maps = new HashMap();
                for (UserInfoInterZhiHuiRoleMapCp role : roleList) {
                    if (role.getUserId().equals(userId)) {//用户对应的角色
                        if (StringUtils.isNullOrEmpty(role.getOrgRoleId())) {
                            maps.put(role.getRoleCode(), role.getRoleName());
                        } else {
                            maps.put(role.getOrgRoleId(), role.getRoleName());
                        }
                    }
                }
                addList.add(maps);
                vo.setRoleCodes(addList);
                if (!StringUtils.isNullOrEmpty(roleCode)) {
                    roleCode = roleCode.substring(0, roleCode.length() - 1);
                }
                vo.setRoleCode(roleCode);
                GetUserInfoByjwtVO rlt = list.get(0);
                return rlt;
            }
        }
        return null;
    }

    @Override
    public UserDictDto getuserbyidcmsnew(Long userId, String userOrgId) {
//        String messageFormat = BaseDataCommonConstants.USER_CACHE_USERID_CMS;
//        Object userDictDto = redisClient.hget(messageFormat, userId.toString());
        Object userDictDto = null;
        //所有数据
        userDictDto = userMapper.getUserByIdCMSNew(userId, userOrgId);
        logger.info("查询用户Dto:{}", userDictDto);
        if (userDictDto == null) {
            return null;
        }
        return JSONUtil.jsonToObj(JSONUtil.objectToJson(userDictDto), UserDictDto.class);
    }

    /**
     * 根据租户及账号ID获取用户信息
     *
     * @param appId
     * @param userId
     * @return com.yonyou.cyx.framework.bean.dto.user_info.LoginInfoDto
     * @author zhangxianchao
     * @since 2018/9/14 0014
     */
    @Override
    @Transactional(readOnly = true)
    public LoginInfoDto getUserInfoByUserId(String appId, Long userId) {
        LoginInfoDto loginInfoDto = userMapper.getUserInfoById(appId, userId);
        logger.debug("获取经销商信息结果：{}", loginInfoDto);
        return loginInfoDto;
    }

    /**
     * 根据角色类别获取用户信息信息
     *
     * @param role 角色类别
     * @return
     * @author 李贺
     * @since 2019/9/4
     */
    @Override
    public List<UserAndRoleDTO> getUserListByRole(Integer role) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        List<UserAndRoleDTO> userandroledtos = userMapper.getUserListByRole(loginInfoDto.getCompanyId(), loginInfoDto.getAppId(), role);
        logger.debug("根据角色类别获取用户信息信息结果：{}", userandroledtos);
        return userandroledtos;
    }

    /**
     * 提供索赔接口 技术支持
     *
     * @param role 角色类别
     * @return
     * @author 谢志恺
     * @since 2021/3/5
     */
    @Override
    public List<UserAndRoleClaimDTO> getUserListByRoleClaim(String role) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        List<UserAndRoleClaimDTO> userandroledtos = userMapper.getUserListByRoleClaim(loginInfoDto.getCompanyId(), loginInfoDto.getAppId(), role);
        logger.debug("根据角色类别获取用户信息信息结果：{}", userandroledtos);
        return userandroledtos;
    }

    @Override
    @Transactional(readOnly = true)
    public LoginInfoDto getAppUserInfo(String appId, String token, String userAgent) {
        logger.debug("token:{},userAgent{}", token, userAgent);
        if (redisClient.exists(token)) {
            Object jwtInfo = redisTemplate.opsForValue().get(token);
            if (jwtInfo != null) {
                // 取得登录账号
                logger.info("jwtInfo:{}", JSONUtil.objectToJson(jwtInfo));
                JSONArray jwtInfoJson = (JSONArray) jwtInfo;
                logger.info("jwtInfoObject:{}", JSONUtil
                        .objectToJson(jwtInfoJson.getJSONObject(1)));
                logger.info("jwtInfoObject:{}", JSONUtil
                        .objectToJson(jwtInfoJson.getJSONObject(1).getJSONArray("param")));
                JSONArray jwtParam = jwtInfoJson.getJSONObject(1).getJSONArray("param");
                Long userId = jwtParam.getJSONObject(1).getLong("userId");

                if (userAgent != null) {
                    String messageFormat = MessageFormat.format(BaseDataCommonConstants.LOGIN_CACHE_USERID, userAgent);
                    Object loginInfoDtoRds = redisClient.hget(messageFormat, userId.toString());
                    if (null != loginInfoDtoRds) {
                        return JSONUtil.jsonToObj(JSONUtil.objectToJson(loginInfoDtoRds), LoginInfoDto.class);
                    }
                }

                LoginInfoDto result = userLoginService.getLoginInfoDto(userId.toString(), userAgent, false); // getUserInfoByUserId(appId, userId);
                if (result == null) {
                    throw new ServiceBizException("用户不存在, appId@userCode:{}", appId + "@" + userId);
                }
                return result;
            } else {
                throw new ServiceBizException("--jwt已失效");
            }
        } else {
            throw new ServiceBizException("jwt不存在！");
        }
    }

    /**
     * 新增user
     *
     * @author 李贺
     * @date 2019年9月11日
     */
    @Override
    public void addUser(UserPO userpo) {
        userMapper.insert(userpo);
    }

    @Override
    public UserInfoVO getUserInfoByUserId(Long userId) {
        List<UserInfoVO> list = userMapper.getUserInfoByUserId(userId);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    @Transactional(readOnly = true)
    public List<UserInfoVO> getUserInfoList(Set<String> userIdSet) {
        if (null == userIdSet || 0 == userIdSet.size()) {
            List<UserInfoVO> rl = new ArrayList<>();
            return rl;
        }
        return ListUtils.emptyIfNull(userMapper.getUserInfoList(userIdSet));
    }

    /**
     * 根据用户的userOrgId 查询用户权限
     *
     * @author 李贺
     * @date 2019年9月23日
     */
    @Override
    public Map<String, Object> userPermission(Long userOrgId, String dataSource) {
        Map<String, Object> userData = new HashMap<>();
        Integer isFixed = ManageDictCodeConstants.STATUS_IS_YES;
        String[] idsArray = {Long.toString(userOrgId)};
        Map<String, Object> params = new HashMap<>();
        params.put("idsArray", idsArray);
        Map<String, String> checkbox = queryMenuCtrl(ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, params);// you
        List<CommonTreeVO> orgList = queryPermissionMenu(ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, params, isFixed);
        userData.put("treejson", orgList);
        userData.put("checkbox", checkbox);
        userData.put("treeMenuAction", findMenuAction(ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, params));
        userData.put("treeMenuRange", findMenuRange(ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, params));

        return userData;
    }

    /**
     * @author ：李贺
     * @date ：2019/9/24
     * @description：重置密码
     */
    @Override
    @Transactional
    public void resetPassword(String employeeNo, String password) {
        Integer type = 0;
        // CMS 屏蔽重置密码 -随机密码 固定 a12345678 START
        if (StringUtils.isNullOrEmpty(password)) {
            /*
            char[] chars = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM".toCharArray();
            StringBuilder passwordBuilder = new StringBuilder();
            for (int i = 0; i < 7; i++) {
                if (i < 2) {
                    int i1 = RandomUtils.nextInt(0, chars.length);
                    passwordBuilder.append(chars[i1]);
                } else {
                    Integer in = RandomUtils.nextInt(0, 10);
                    passwordBuilder.append(in);
                }
            }
            password = passwordBuilder.toString();
            */
            password = "a12345678";
            //type = 1;
        }
        // CMS 屏蔽重置密码 -随机密码 固定 a12345678 END

        String md5Password = MD5Util.getEncryptedPwd(password);

        UserEmpInfoVO userEmpInfoVO = userMapper.findInfo(employeeNo);

        UserPO userpo = userMapper.selectById(userEmpInfoVO.getUserId());
        userpo.setPassword(md5Password);
        userMapper.updateById(userpo);
        if (type.equals(1)) {
            String phone = userEmpInfoVO.getMobilePhone();
            sendpasswordSms(password, phone);
        }
        jwtService.delJwtInfo(userpo.getUserId().toString());
    }

    /**
     * @description：短信登录密码发送
     * @author ：李贺
     * @date ：Created in 2019/9/19
     * @modified By：
     */
    public void sendpasswordSms(String password, String phone) {
        //CMS 屏蔽短信发送密码 -- START
//        SmsPushDTO smsPushDTO = new SmsPushDTO();
//        smsPushDTO.setMobiles(phone);
//        smsPushDTO.setTemplateId(smsTemplateId2);
//        Map<String, String> params = new HashMap<>();
//        params.put("1", password);
//        smsPushDTO.setParamMap(params);
//        String f4Result = pushService.sendSms(smsPushDTO);
//        logger.info("短信发送返回结果f4Result：{}", f4Result);
        //CMS 屏蔽短信发送密码 -- END
    }

    @Override
    public IPage<UserInfoVO> getUserInfoByParams2(Page<UserInfoVO> page, UserParamDTO userParamDTO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("appId", loginInfoDto.getAppId());
        param.put("userCode", userParamDTO.getUserCode());
        param.put("employeeName", userParamDTO.getEmployeeName());
        param.put("mobilePhone", userParamDTO.getMobilePhone());
        param.put("eMail", userParamDTO.geteMail());
        param.put("orgId", userParamDTO.getOrgId());
        param.put("orgType", userParamDTO.getOrgType());
        param.put("dataType", userParamDTO.getDataType());
        param.put("dataSources", userParamDTO.getDataSources());
        List<UserInfoVO> list = userMapper.getUserInfoByParams(page, param);
        page.setRecords(list);
        return page;
    }

    @Override
    public Map<String, List<UserPermissionActionListDTO>> getUserPermissionAction() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        List<UserPermissionActionListDTO> list = userMapper.getUserPermissionAction(loginInfoDto.getUserOrgId(), ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER);
        Map<String, List<UserPermissionActionListDTO>> map = new HashMap<>();
        for (UserPermissionActionListDTO userPermissionActionListDTO : list) {
            if (map.get(userPermissionActionListDTO.getMenuId()) == null) {
                List<UserPermissionActionListDTO> listDto = new ArrayList<>();
                listDto.add(userPermissionActionListDTO);
                map.put(userPermissionActionListDTO.getMenuId(), listDto);
            } else {
                map.get(userPermissionActionListDTO.getMenuId()).add(userPermissionActionListDTO);
            }
        }

        return map;
    }

    @Override
    public List<com.yonyou.cyxdms.sysmanage.client.vo.user.UserInfoVO> getUsersByPosition(Long menuId, List<Integer> positionCodes, String userPhone) {
        logger.debug("通过菜单id职位查询人员");
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Long companyId = loginInfoDto.getCompanyId();
        List<com.yonyou.cyxdms.sysmanage.client.vo.user.UserInfoVO> userinfovos = new ArrayList<>();
        Long orgId = loginInfoDto.getOrgId();
        Long userOrgId = loginInfoDto.getUserOrgId();
        String appId = loginInfoDto.getAppId();
        Integer rangeCode = permissionMenuRangeMapper.findRangeBymenuId(ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, userOrgId, appId, menuId);
        if (StringUtils.isNullOrEmpty(rangeCode)) {
            rangeCode = ManageDictCodeConstants.ORG_ALL;
        }
        if (rangeCode == ManageDictCodeConstants.IAM_ORGANIZATION) {
            userinfovos = empMapper.queryUserByOrgId(orgId, positionCodes, companyId, userPhone);
        } else if (rangeCode == ManageDictCodeConstants.IAM) {
            com.yonyou.cyxdms.sysmanage.client.vo.user.UserInfoVO userInfoVO = new com.yonyou.cyxdms.sysmanage.client.vo.user.UserInfoVO();
            userInfoVO.setOrgId(orgId);
            userInfoVO.setUserCode(loginInfoDto.getUserCode());
            userInfoVO.setUserId(loginInfoDto.getUserId());
            userInfoVO.setUserName(loginInfoDto.getUserName());
            Long empId = loginInfoDto.getEmpId();
            EmpPo empPo = empMapper.selectById(empId);
            userInfoVO.setMobilePhone(empPo.getMobilePhone());
            userinfovos.add(userInfoVO);
        } else if (rangeCode == ManageDictCodeConstants.IAM_ORGANIZATION_SUB) {
            String orgs = orgMapper.getOrgs(orgId);
            String[] orgIds = orgs.split(",");
            if (orgIds.length != 0) {
                //审批分配去掉离职人员
                if (menuId == 202050) {
                    userinfovos = empMapper.queryUserByOrgIdsSp(orgIds, positionCodes, companyId, userPhone);
                } else {
                    userinfovos = empMapper.queryUserByOrgIds(orgIds, positionCodes, companyId, userPhone);
                }
            }
        } else if (rangeCode == ManageDictCodeConstants.ORG_ALL) {

            CompanyPO companypo = companyMapper.selectById(companyId);
            Integer companyType = companypo.getCompanyType();
            if (companyType == ManageDictCodeConstants.ORG_TYPE_FACTORY) {
                Integer orgId1 = companypo.getOrgId();
                String orgs = orgMapper.getOrgs(orgId1.longValue());
                String[] orgIds = orgs.split(",");
                if (orgIds.length != 0) {
                    userinfovos = empMapper.queryUserByOrgIds(orgIds, positionCodes, companyId, userPhone);
                }
            } else {
                String ownerCode = loginInfoDto.getOwnerCode();
                //202041分配   202035确认到店选择顾问  202014创建线索
                if (menuId == 202041 || menuId == 202035 || menuId == 202014) {
                    userinfovos = empMapper.queryUserByOwnerCodeFp(ownerCode, companyId, userPhone, positionCodes);
                } else {
                    userinfovos = empMapper.queryUserByOwnerCode(ownerCode, companyId, userPhone, positionCodes);
                }
            }
        }
        return userinfovos;
    }

    @Override
    public List<com.yonyou.cyxdms.sysmanage.client.vo.user.UserInfoVO> getUsersByManager(Long menuId, List<Integer> positionCodes, String userPhone) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Long companyId = loginInfoDto.getCompanyId();
        List<com.yonyou.cyxdms.sysmanage.client.vo.user.UserInfoVO> userinfovos = new ArrayList<>();
        Long orgId = loginInfoDto.getOrgId();
        Long userOrgId = loginInfoDto.getUserOrgId();
        String appId = loginInfoDto.getAppId();

        List<Integer> queryPositionCodes = new ArrayList<Integer>();
        for (Integer code : positionCodes) {
            if (code.intValue() == 10061019) {    //如果是网销经理
                queryPositionCodes.add(10061012);    //存入网销顾问
            }

            if (code.intValue() == 10061032 || code.intValue() == 10061013) {    //如果是销售总监或展厅主管
                queryPositionCodes.add(10061015);    //存入销售顾问
            }
        }

        if (queryPositionCodes != null && queryPositionCodes.size() > 0) {
            String orgs = orgMapper.getOrgs(orgId);
            String[] orgIds = orgs.split(",");
            if (orgIds.length != 0) {
                //转移去掉离职人员
                if (menuId == 202042) {
                    userinfovos = empMapper.queryUserByPositionCodesZy(queryPositionCodes, companyId, userPhone);
                } else {
                    userinfovos = empMapper.queryUserByPositionCodes(queryPositionCodes, companyId, userPhone);
                }
            }
        }

        return userinfovos;
    }

    @Override
    public List<DealerUserVO> getDealerUser() {
        LoginInfoDto loginInfoDTO = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        // QueryWrapper<DealerInfoPO> dealerInfoPOQueryWrapper = new QueryWrapper<>();
        // dealerInfoPOQueryWrapper.select("org_id").eq("dealer_code", loginInfoDTO.getOwnerCode()).eq("app_id", loginInfoDTO.getAppId());
        // DealerInfoPO dealerInfoPO = dealerInfoMapper.selectOne(dealerInfoPOQueryWrapper);
        // if (dealerInfoPO == null) {
        //     throw new ServiceBizException("所属公司在经销商信息中查询不到!");
        // }
        // Integer orgId = dealerInfoPO.getOrgId();
        // String orgs = orgMapper.getOrgs(orgId.longValue());
        String[] idsArray = null;
        if (!StringUtils.isNullOrEmpty(loginInfoDTO.getOrgIds())) {
            idsArray = loginInfoDTO.getOrgIds().split(",");
        }
        return dealerInfoMapper.getDealerUser(loginInfoDTO.getOrgId().intValue(), idsArray);
    }

    @Override
    public Integer getAppPosition() {
        LoginInfoDto loginInfoDTO = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Long userOrgId = loginInfoDTO.getUserOrgId();
        List<Integer> appPositions = userOrgMapper.queryRoleByUserOrgId(userOrgId);
        return appPositions.size() == 0 ? null : appPositions.get(0);
    }

    /**
     * 根据userId和userOrgId返回角色类别
     *
     * @date 2019-10-28  adu
     */
    @Override
    public Map<String, Object> getRoleTypeParams(Integer userId, Integer orgId) {
        return userMapper.getRoleTypeParams(userId, orgId);
    }

    /**
     * @author ：maxingjian
     * @date ：2019/11/06
     * @description：获取用户的个人参数配置
     */
    @Override
    public Map<String, List<String>> getUserPermissionCtrl() {
        LoginInfoDto loginInfoDTO = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        List<UserPermissionCtrlVO> list = userOrgMapper.getUserPermissionCtrl(
                loginInfoDTO.getUserOrgId() == null ? StringUtils.EMPTY_STRING : String.valueOf(loginInfoDTO.getUserOrgId()), loginInfoDTO.getAppId());
        Map<String, List<String>> map = new HashMap<>();
        for (UserPermissionCtrlVO userPermissionCtrlVO : list) {
            if (map.get(userPermissionCtrlVO.getType()) == null) {
                List listDto = new ArrayList<>();
                listDto.add(userPermissionCtrlVO.getCtrlCode());
                map.put(userPermissionCtrlVO.getType(), listDto);
            } else {
                map.get(userPermissionCtrlVO.getType()).add(userPermissionCtrlVO.getCtrlCode());
            }
        }
        return map;
    }

    /**
     * 将所有的failureNum改为0
     *
     * @author 李贺
     * @date 2019年11月19日
     */
    @Override
    @Transactional
    public Long updateFailureNum() {
        return userMapper.updateFailureNum();
    }

    /**
     * 获取用户数量
     *
     * @author MAXINGJIAN
     * @date 2019年11月20日
     */
    @Override
    public Long getUserCount() {
        LoginInfoDto loginInfoDTO = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        LambdaQueryWrapper<UserPO> queryWrapper = new QueryWrapper<UserPO>().lambda();
        queryWrapper.eq(UserPO::getAppId, loginInfoDTO.getAppId());
        return userMapper.selectCount(queryWrapper).longValue();
    }

    /**
     * 通过userid获取经理的userid
     *
     * @author maxingjian
     * @date 2019年11月22日
     */
    @Override
    public List<String> getManagerIdByUserId(String userId, String positionCode, String orgId) {

        String[] positionCodes = null;
        if (!StringUtils.isNullOrEmpty(positionCode)) {
            positionCodes = positionCode.split(",");
        }
        return userOrgMapper.getManagerIdByUserId(userId, positionCodes, orgId);
    }

    @Override
    public List<Long> getUserIdByName(String appId, String ownerCode, String name) {
        return userOrgMapper.getUserIdByName(appId, ownerCode, name);
    }

    @Override
    public List<Long> getUserIdByNameAndPositionCode(String appId, String ownerCode, String name) {
        return userOrgMapper.getUserIdByNameAndPositionCode(appId, ownerCode, name);
    }

    @Override
    public UserDTO getUserIdByUserCode(String userCode, String appId) {
        LambdaQueryWrapper<UserPO> queryWrapper = new QueryWrapper<UserPO>().lambda().eq(UserPO::getUserCode, userCode).eq(UserPO::getAppId, appId);
        UserPO userpo = this.userMapper.selectOne(queryWrapper);
        UserDTO userDTO = null;
        if (userpo != null) {
            userDTO = BeanMapperUtil.copyProperties(userpo, UserDTO.class);
            userDTO.setUserId(userpo.getUserId().longValue());

        }

        return userDTO;
    }

    /**
     * 获取所有人员（翻译用）
     *
     * @author maxingjian
     * @date 2019年12月31日
     */
    @Override
    public List<CompanyUserVO> getAllUser() {
        LoginInfoDto loginInfoDTO = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return userMapper.getAllUser(loginInfoDTO.getCompanyId(), loginInfoDTO.getAppId());
    }

    /**
     * 通过职位获取角色类别
     *
     * @author maxingjian
     * @date 2019年12月31日
     */
    @Override
    public String getPositionCodeByUserOrgId(Long userOrgId) {
        return userMapper.getPositionCodeByUserOrgId(userOrgId);
    }

    @Override
    public List<UserRoleVO> getRoleInfoByCompanyId(String companyId, String appId) {
        return userMapper.getRoleInfoByCompanyId(companyId, appId);
    }

    @Override
    public List<String> getUserIdByMenuId(String menuId, String appId, String userId, String userCode) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        //LoginInfoDto loginInfoDto = userMapper.getUserInfoByCode(userCode, appId);
        String orgIds = loginInfoDto.getOrgIds();
        String[] orgIdList = orgIds.split(",");
        Map<String, Object> params = new HashMap<>();
        String[] idsArray = {loginInfoDto.getUserOrgId().toString()};
        params.put("idsArray", idsArray);
        List<Map> listmap = permissionMenuRangeMapper.findMenuRange(ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, params);
        String menuRangeId = "";
        for (Map map : listmap) {
            if (map.get("menuId").toString().equals(menuId)) {
                menuRangeId = map.get("rangeCode").toString();
            }
        }

        Map<String, Object> queryCondition = new HashMap<>();
        queryCondition.put("MENU_ID", menuId);
        queryCondition.put("APP_ID", appId);
        queryCondition.put("MENU_RANGE_ID", menuRangeId);
        List<MenuRangePO> poList = menuRangeMapper.selectByMap(queryCondition);
        List<String> rlt = new ArrayList<String>();
        if (poList.size() > 0) {
            MenuRangePO po = poList.get(0);
            Integer rangeCode = po.getRangeCode();
            //如果是本人
            if (ManageDictCodeConstants.IAM == rangeCode) {
                return rlt;
            }
            //如果是本组织
            else if (ManageDictCodeConstants.IAM_ORGANIZATION == rangeCode) {
                Long orgId = loginInfoDto.getOrgId();
                rlt.add(orgId.toString());
                return rlt;
            }
            //如果是本组织及一下
            else if (ManageDictCodeConstants.IAM_ORGANIZATION_SUB == rangeCode) {
                for (String a : orgIdList) {
                    rlt.add(a);
                }
                return rlt;
            }
            //如果是所有
            else if (ManageDictCodeConstants.ORG_ALL == rangeCode) {
                return null;
            }
        }

        return null;
    }

    @Override
    public void sendConsultant() {
        ConsultantParamVo param = new ConsultantParamVo();
        List<ConsultantVo> list = userMapper.selectConsultantInfo();
        for (ConsultantVo vo : list) {
            //在职 离职
            Integer status = vo.getStatus();
            if (null != status && 10081001 == status) {
                vo.setStatus(1);
            } else if (null != status && 10081002 == status) {
                vo.setStatus(0);
            }

            //翻译性别
            String sex = vo.getSex();
            if (null != sex && "10021001".equals(sex)) {
                vo.setSex("M");
            } else if (null != sex && "10021002".equals(sex)) {
                vo.setSex("F");
            } else {
                vo.setSex(null);
            }

            LocalDateTime dataTime = vo.getDataTime();
            if (null != dataTime) {
                Long bornData = dataTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
                vo.setBornData(bornData);
            }
        }

        Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        RestServiceRequestDto requestDto = new RestServiceRequestDto();
        Map<String, String> params = new HashMap<>();
        params.put("appkey", appkey);
        params.put("signt", milliSecond.toString());
        String sign = null;
        try {
            sign = SignatureGenerator.generate("vehicle-market/internal/sale/syncSalesConsultant", params, secretkey);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        String url = sendConsultantToAFAPPUrl + "appkey=" + appkey + "&signt=" +
                milliSecond + "&sign=" + sign;
        requestDto.setUrl(url);
        param.setConsultants(list);
        String json = JSONObject.toJSONString(param);
        logger.info("发送至AFAPP的顾问集合++++++" + json);
        requestDto.setBody(param);
        logger.info("开始获取数据");
        RestServiceResponseDto request2 = httpService.postJsonRequest(requestDto); // 发送请求  同步发送
    }

    @Override
    public List<UserEmpVO> getNameByIds(String userIds) {
        if (!StringUtils.isNullOrEmpty(userIds)) {
            String[] split = userIds.split(",");
            if (split.length == 0) {
                return null;
            }
            List<UserEmpVO> nameByIds = userMapper.findNameByIds(split);
            return nameByIds;
        }
        return null;
    }

    @Override
    public List<UserEmpVO> findUserByRole(String roleCode, String roleId, String ownerCode, String companyId, String appId) {
        Map params = new HashMap();
        params.put("roleCode", roleCode);
        params.put("roleId", roleId);
        params.put("ownerCode", ownerCode);
        params.put("companyId", companyId);
        params.put("appId", appId);
        List<UserEmpVO> res = userMapper.findUserByRole(params);
        return res;
    }

    @Override
    public Integer checkEmployeeStatus(String appId, Long userId){
        return userMapper.checkEmployeeStatus(appId,userId);
    }

    @Override
    public List<UserEmpVO> getNameByAppId(String appId) {
        List<UserEmpVO> nameByIds = userMapper.findNameByAppId(appId);
        return nameByIds;
    }
}
